<!-- 桌台列表组件 -->
<template>
  <div>
    <div class="desktop-content" :class="{ fullWidth: isFood ? false : true }">
      <div class="desktop-column-box">
        <!-- 分类和搜索 -->
        <div class="pagingAndSearch-box">
          <div class="paging-list-box">
            <div
              class="paging-list-item"
              :class="{ 'paging-list-item-active': currentActiveIndex === pagingIndex }"
              @click="handleSelectPaging(pagingIndex, pagingItem)"
              v-for="(pagingItem, pagingIndex) in desktopCategoryList"
              :key="pagingItem.id"
            >
              <el-tooltip class="item" effect="dark" :content="pagingItem.name" placement="top">
                <div class="name">{{ pagingItem.name }}</div>
              </el-tooltip>
            </div>
            <div class="paging-list-btn">
              <img
                class="left-btn"
                @click="oneCatePreviousPage"
                src="@/assets/images/home/page-left-icon.png"
                alt=""
              />
              <img
                @click="oneCateNextPage"
                class="right-btn"
                src="@/assets/images/home/page-right-icon.png"
                alt=""
              />
            </div>
          </div>
          <div class="search-box">
            <div class="content1">
              <img src="@/assets/images/home/sousuo-icon.png" alt="" />
              <input
                @input="onSearch"
                v-model.trim="desktopFilterQuery.name"
                type="text"
                placeholder="搜索桌台号"
              />
            </div>
          </div>
        </div>
        <!-- 标签 -->
        <div class="tag-select-box">
          <div class="tag-btn-list">
            <div
              class="tag-btn-item"
              :class="{ 'tag-btn-item-active': tagActiveIndex === tagIndex }"
              @click="handleSelectTag(tagIndex, tagItem)"
              v-for="(tagItem, tagIndex) in tagButtonList"
              :key="tagItem.name + tagIndex"
            >
              {{ tagItem.name }}
            </div>
          </div>
          <div class="tag-status-list">
            <div
              class="tag-status-item"
              :style="{
                color: tagStutasColorEnum[statusItem.status]
              }"
              v-for="statusItem in tagStutasList"
              :key="statusItem.name"
            >
              <div
                :style="{
                  background: tagStutasColorEnum[statusItem.status]
                }"
                class="circular"
              ></div>
              <div class="name">{{ statusItem.name }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 桌台列表 -->
      <div class="desktop-scroll-list" v-loading="listLoading">
        <div class="scroll-list-item-content" v-if="!isEmptyDesktopList">
          <div
            class="scroll-list-item"
            v-for="(desk, index) in desktopList"
            :key="index"
            @click="handleSelectTable(desk)"
            :style="{
              'border-color':
                desk &&
                desk.is_use.value === 1 &&
                desk.recordInfo &&
                desk.recordInfo.status &&
                desk.recordInfo.status.value
                  ? deskOrderStatus[desk.recordInfo.status.value]
                  : deskUseStatus[desk.is_use.value]
            }"
          >
            <div
              class="title-box"
              :style="{
                background:
                 calculateBackgroundStatus(desk)
              }"
            >
              <div class="name-box">
                <div
                  class="name"
                  v-if="
                    desk &&
                    desk.is_use.value === 1 &&
                    desk.recordInfo &&
                    desk.recordInfo.status &&
                    desk.recordInfo.status.value
                  "
                >
                  {{ calculateText(desk) }}
                </div>
                <div class="name" v-else>{{ desk.is_use.text }}</div>
                <img
                  class="lock-icon"
                  v-if="
                    desk.recordInfo &&
                    desk.recordInfo.is_lock &&
                    desk.recordInfo.is_lock.value === 1
                  "
                  src="@/assets/images/home/lock-icon.png"
                  alt=""
                />
              </div>
              <div class="count" v-if="desk.capacity != 0">
                <span v-if="desk && desk.hadRecordList && desk.recordInfo">
                  {{ desk.recordInfo.use_num || '0' }}</span
                >
                <span v-else>{{ desk.use_num || '0' }}</span
                >/<span>{{ desk.capacity }}人</span>
              </div>
            </div>
            <div class="desc-box">
              <div class="numberAndTag">
                <el-tooltip
                  class="item"
                  v-if="desk.recordInfo && desk.recordInfo.desk_name"
                  effect="dark"
                  :content="desk.recordInfo.desk_name"
                  placement="top"
                >
                  <div class="number">{{ desk.recordInfo.desk_name }}</div>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  v-else-if="desk.name"
                  effect="dark"
                  :content="desk.name"
                  placement="top"
                >
                  <div class="number">{{ desk.name }}</div>
                </el-tooltip>
                <div class="tag" v-if="desk.recordInfo && desk.recordInfo.recordType">
                  {{ desk.recordInfo.recordType }}
                </div>
              </div>
              <div class="price" v-if="desk && desk.recordInfo">
                ￥{{ desk.recordInfo.pay_money }}元
              </div>
              <div
                class="time1"
                v-if="desk && desk.hadRecordList && desk.recordInfo && desk.recordInfo.start_time"
              >
                开台时长：
                <span
                  v-if="
                    desk &&
                    desk.recordInfo &&
                    desk.recordInfo.start_time &&
                    desk.recordInfo.start_time.long.day
                  "
                  >{{ desk.recordInfo.start_time.long.day }}天</span
                >
                <span
                  v-if="
                    desk &&
                    desk.recordInfo &&
                    desk.recordInfo.start_time &&
                    desk.recordInfo.start_time.long.hour
                  "
                  >{{ desk.recordInfo.start_time.long.hour }}时</span
                >
                <span
                  v-if="
                    desk.recordInfo &&
                    desk.recordInfo.start_time &&
                    desk.recordInfo.start_time.long.minute
                  "
                  >{{ desk.recordInfo.start_time.long.minute }}分</span
                >
              </div>
              <div
                class="time2"
                v-if="desk && desk.hadRecordList && desk.recordInfo && desk.recordInfo.start_time"
              >
                开台时间：{{ desk.recordInfo.start_time.time }}
              </div>
            </div>

            <div class="book-info-box" v-if="!isEmpty(desk.bookInfo)">
              <div class="money">订金：￥{{ desk.bookInfo.book_money }}</div>
              <div class="person">预订人：{{ desk.bookInfo.user_name }}</div>
              <div class="phone">电话：{{ desk.bookInfo.mobile }}</div>
              <div class="time">预留{{ desk.bookInfo.keep_time }}分钟</div>
            </div>
            <!-- 选中桌台的图片 -->
            <img
              v-show="desk.isChecked"
              class="choose-img"
              src="@/assets/images/home/xuanzhongzhuotai.png"
              alt=""
            />
          </div>
          <!-- 当一行有3个以上的元素时，添加占位元素 ，纯样式专用，无影响其他逻辑 -->
          <div
            class="scroll-list-item-zhanwei"
            v-for="val in ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7']"
            :key="val"
          ></div>
        </div>
        <!-- 暂无数据的组件 -->
        <div class="no-data-box" v-if="isEmptyDesktopList">
          <NotData desc="暂无桌台数据" />
        </div>
      </div>

      <!-- 显示对应的桌台数量 -->
      <div class="desktop-count-box">
        <div class="left" v-show="desktopListTotal > 0">共{{ desktopListTotal }}台</div>
        <div class="right">
          <el-pagination
            v-show="desktopListTotal > 0"
            :total="desktopListTotal"
            v-model:current-page="desktopFilterQuery.page"
            v-model:page-size="desktopFilterQuery.limit"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
            background
            :page-sizes="[16, 21, 75, 100]"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
      <!-- 底部操作按钮 -->
      <div class="desktop-actions-btn-box" :class="{ fullWidth: isFood ? false : true }">
        <div class="btn-list">
          <div class="btn-item" @click="handleAction('isShowMulOpeningDesktopDialog')">
            多台开席
          </div>
          <template v-if="isFood">
            <div class="btn-item" @click="handleAction('isShowTransferDesktopDialog')">转台</div>
            <div class="btn-item" @click="handleAction('isShowShareDesktopDialog')">搭台</div>
            <div class="btn-item" @click="handleAction('isShowMergeDesktopDialog')">并台</div>
            <div class="btn-item" @click="handleAction('isShowRevokeDesktopDialog')">撤台</div>
          </template>
        </div>
      </div>
    </div>

    <!-- 多台开席的弹窗组件 -->
    <MulOpeningDesktopDialog
      v-model="isShowMulOpeningDesktopDialog"
      @updateList="getDeskListData(true)"
    />

    <!-- 单席开台/空桌开台弹窗 -->
    <OpeningDesktopDialog
      v-model="isShowOpeningDesktopDialog"
      :desk="openingDesk"
      @success="getDeskListData(true)"
    />

    <!-- 桌台进行转台操作的弹窗组件 -->
    <TransferDesktopDialog
      v-model="isShowTransferDesktopDialog"
      :deskDetail="currentDeskDetail"
      @success="getDeskListData(true)"
    />

    <!-- 桌台进行搭台操作的弹窗组件 -->
    <ShareDesktopDialog
      v-model="isShowShareDesktopDialog"
      :deskDetail="currentDeskDetail"
      @success="getDeskListData(true)"
    />

    <!-- 桌台进行并台操作的弹窗组件 -->
    <MergeDesktopDialog
      v-model="isShowMergeDesktopDialog"
      :deskDetail="currentDeskDetail"
      @success="getDeskListData(true)"
    />

    <!-- 开班弹框 -->
    <WorkingDialog v-model="isShowWorkingDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { debounce, isEmpty } from '@/utils/toolsValidate'
import { fetchDeskList, fetchCategoryList, clearDesk } from '@/api/desktop'
import { useUserStore } from '@/stores/user'
import { bus } from '@/utils/bus'
import MulOpeningDesktopDialog from './MulOpeningDesktopDialog/Index.vue'
import OpeningDesktopDialog from './OpeningDesktopDialog/Index.vue'
import MergeDesktopDialog from './MergeDesktopDialog.vue'
import ShareDesktopDialog from './ShareDesktopDialog.vue'
import TransferDesktopDialog from './TransferDesktopDialog.vue'
import { DESK_USE_STATUS, DESK_ORDER_STATUS, DESK_STATUS_TEXT } from '@/constants/desktopStatus'
import MessageTips from '@/components/messageTips'
import NotData from '@/components/NotData/Index.vue'
import WorkingDialog from '@/components/layout/WorkingDialog/Index.vue'
import { deskBookOpenBookDesk } from '@/api/book'
const props = defineProps({
  isFood: {
    type: Boolean,
    default: false
  },
  // 默认选中的桌台记录ID（有记录的桌台 recordInfo.id）
  selectedRecordId: {
    type: [String, Number],
    default: null
  }
})

// 当前选中的桌台详情
const currentDeskDetail = ref(null)

// 分页分类专用索引
const currentActiveIndex = ref(0)

// 标签按钮列表
const tagButtonList = [
  { name: '全部', status: 3 },
  { name: '空闲', status: 0 },
  { name: '在用', status: 1 },
  { name: '预订', status: 2 }
]

// 标签按钮点击选中索引下标
const tagActiveIndex = ref(0)

// 标签状态列表
const tagStutasList = [
  { name: '空闲', status: 0 },
  { name: '催菜', status: 1 },
  { name: '等叫', status: 2 },
  { name: '即食', status: 3 },
  { name: '预订', status: 4 },
  { name: '已预结', status: 5 }
]

// 标签状态颜色枚举
const tagStutasColorEnum = {
  0: '#999999', // 空闲 - 灰色
  1: '#AA535C', // 催菜 - 红色
  2: '#CBA699', // 等叫 - 棕色
  3: '#7A8972', // 即食 - 绿色
  4: '#EFB176', // 预订 - 橙色
  5: '#665bbd' // 已预结 - 深灰色
}

// 桌台操作的弹窗相关数据
// 弹框开关（v-model）
const isShowMulOpeningDesktopDialog = ref(false)
const isShowOpeningDesktopDialog = ref(false)
const isShowMergeDesktopDialog = ref(false)
const isShowShareDesktopDialog = ref(false)
const isShowTransferDesktopDialog = ref(false)
const isShowWorkingDialog = ref(false)

// 计算背景状态
const calculateBackgroundStatus = (desk: any) => {
  if (
    desk &&
    desk.is_use.value === 1 &&
    desk.recordInfo &&
    desk.recordInfo.is_lock &&  
    desk.recordInfo.is_lock.value === 2) {
      return '#03297c'
    }
  return desk &&
    desk.is_use.value === 1 &&
    desk.recordInfo &&
    desk.recordInfo.status &&
    desk.recordInfo.status.value
      ? deskOrderStatus[desk.recordInfo.status.value]
      : deskUseStatus[desk.is_use.value]
}
const calculateText = (desk: any) => {
  if (
    desk &&
    desk.is_use.value === 1 &&
    desk.recordInfo &&
    desk.recordInfo.is_lock &&  
    desk.recordInfo.is_lock.value === 2) {
      return '已预结'
    }
  return deskStatusText[desk.recordInfo.status.value] 
}


// 开台弹窗绑定的桌台
const openingDesk = ref<any | null>(null)

// 桌台筛选查询的相关数据
const desktopFilterQuery = ref({
  // 桌台名称
  name: null,
  // 桌台状态
  is_use: null,
  // 分页默认第一页
  page: 1,
  // 分区id
  region_id: null,
  // 分类id
  category_id: null,
  // 分页数据显示条数  limit默认16条
  limit: 16
})

const emit = defineEmits(['selectTable'])
const userStore = useUserStore()

// 桌台分类列表
const desktopCategoryList = ref([])

// 桌台列表
const desktopList = ref([])

// 分页列表总条数
const desktopListTotal = ref(0)

// 列表加载状态
const listLoading = ref(false)

// 桌台分类列表分页相关
const deskCategoryPageQuery = ref({
  // 一级分类的分页
  page: 1,
  limit: 4
})

// 判断一级分类是否还能继续下一页操作分页
const deskOneCategoryLastPage = ref(0)

// 桌台的使用状态颜色的颜色枚举
const deskUseStatus = DESK_USE_STATUS

// 桌台订单状态的颜色枚举
const deskOrderStatus = DESK_ORDER_STATUS

// 桌台状态文字
const deskStatusText = DESK_STATUS_TEXT
// 计算属性：是否为空桌台列表
const isEmptyDesktopList = computed(() => {
  return isEmpty(desktopList.value)
})

// 监听当前桌台详情变化
// watch(currentDeskDetail, val => {
//   // 判断是否有桌台详情数据，分页条数改变
//   if (val) {
//     desktopFilterQuery.value.limit = 16
//   } else {
//     desktopFilterQuery.value.limit = 21
//   }
//   // 获取桌台列表数据
//   getDeskListData(true)
// })

// 处理桌台列表刷新事件
const handleDeskListRefresh = () => {
  getDeskListData(true)
}

onMounted(() => {
  // 判断是否有桌台详情数据，分页条数改变
  if (currentDeskDetail.value) {
    desktopFilterQuery.value.limit = 16
  } else {
    desktopFilterQuery.value.limit = 21
  }

  // 获取桌台分类数据
  getDesktopCategoryList()
  // 获取桌台列表数据
  getDeskListData(true)
  
  // 监听桌台列表刷新事件
  bus.on('desk-list-refresh', handleDeskListRefresh)
})

onUnmounted(() => {
  // 移除事件监听
  bus.off('desk-list-refresh', handleDeskListRefresh)
})

// 处理选择分页
const handleSelectPaging = (index: number, item: any) => {
  currentActiveIndex.value = index
  desktopFilterQuery.value.category_id = item.id
  desktopFilterQuery.value.page = 1
  getDeskListData()
}

// 处理选择标签
const handleSelectTag = (index: number, item: any) => {
  tagActiveIndex.value = index
  desktopFilterQuery.value.is_use = item.status
  desktopFilterQuery.value.page = 1
  getDeskListData()
}

// 搜索操作
const onSearch = debounce(() => {
  desktopFilterQuery.value.page = 1
  getDeskListData()
}, 500)

// 上一页分类
const oneCatePreviousPage = () => {
  if (deskCategoryPageQuery.value.page > 1) {
    deskCategoryPageQuery.value.page--
    getDesktopCategoryList()
  }
}

// 下一页分类
const oneCateNextPage = () => {
  if (deskCategoryPageQuery.value.page < deskOneCategoryLastPage.value) {
    deskCategoryPageQuery.value.page++
    getDesktopCategoryList()
  }
}

// 获取桌台分类数据
const getDesktopCategoryList = async () => {
  try {
    const res = await fetchCategoryList(deskCategoryPageQuery.value)
    if (res.status === 200 && !isEmpty(res?.data?.data)) {
      let categoryData = res.data.data
      if (deskCategoryPageQuery.value.page === 1) {
        categoryData.unshift({
          id: 0,
          name: '全部'
        })
      }
      desktopCategoryList.value = categoryData
      // 计算总页数
      if (res.data.total && res.data.per_page) {
        deskOneCategoryLastPage.value = Math.ceil(res.data.total / res.data.per_page)
      }
    } else {
      // API调用成功但没有数据
      desktopCategoryList.value = []
      deskOneCategoryLastPage.value = 0
    }
  } catch (error) {
    console.error('获取桌台分类失败:', error)
    // API调用失败，清空数据
    desktopCategoryList.value = []
    deskOneCategoryLastPage.value = 0
  }
}

// 获取桌台列表数据
const getDeskListData = async (isRefresh = true) => {
  isRefresh && (listLoading.value = true)
  try {
    const res = await fetchDeskList(desktopFilterQuery.value)
    if (res.status === 200 && !isEmpty(res?.data)) {
      // 组装桌台列表
      const desktopArrList = []
      if (!isEmpty(res?.data?.data)) {
        res.data.data.forEach(item => {
          if (isEmpty(item.recordList)) {
            // 标记recordList为空
            item.hadRecordList = false
            item.isChecked = false
            desktopArrList.push(item)
          } else {
            // 标记recordList不为空
            item.hadRecordList = true
            item.recordList.forEach(record => {
              const recordObj = {
                recordInfo: {
                  ...record
                }
              }
              const newItem = { ...item, ...recordObj, isChecked: false }
              desktopArrList.push(newItem)
            })
          }
        })
        desktopList.value = desktopArrList
        desktopListTotal.value = res.data.total
      } else if (!isEmpty(res.data && res.data.length > 0)) {
        res.data.forEach(item => {
          if (isEmpty(item.recordList)) {
            // 标记recordList为空
            item.hadRecordList = false
            item.isChecked = false
            desktopArrList.push(item)
          } else {
            // 标记recordList不为空
            item.hadRecordList = true
            item.recordList.forEach(record => {
              const recordObj = {
                recordInfo: {
                  ...record
                }
              }
              const newItem = { ...item, ...recordObj, isChecked: false }
              desktopArrList.push(newItem)
            })
          }
        })
        desktopList.value = desktopArrList
        desktopListTotal.value = desktopArrList.length
      } else {
        // 排空判断
        desktopList.value = []
        desktopListTotal.value = 0
      }
      // 列表加载完后，尝试根据 selectedRecordId 选中桌台
      if (!userPaging.value) {
        await trySelectDefaultDesk()
      }
    } else {
      // API调用成功但没有数据
      desktopList.value = []
      desktopListTotal.value = 0
    }
  } catch (error) {
    console.error('获取桌台列表失败:', error)
    // API调用失败，清空数据
    desktopList.value = []
    desktopListTotal.value = 0
  } finally {
    listLoading.value = false
  }
}

// 标记：避免递归定位时的重复触发
const locatingSelected = ref(false)
// 标记：用户主动分页/切换，禁止自动跳页
const userPaging = ref(false)

// 尝试在当前页选中；若不在当前页，则跨页查找并跳转到该页
const trySelectDefaultDesk = async () => {
  if (!props.selectedRecordId) return
  const idVal = String(props.selectedRecordId)
  // 1) 先在当前页查找并选中
  const foundInCurrent = desktopList.value.find((d: any) => String(d?.recordInfo?.id) === idVal)
  if (foundInCurrent) {
    desktopList.value.forEach((item: any) => (item.isChecked = false))
    foundInCurrent.isChecked = true
    currentDeskDetail.value = foundInCurrent
    return
  }

  // 2) 不在当前页，且未处于定位中，则跨页查找
  if (locatingSelected.value) return
  locatingSelected.value = true
  try {
    // 优先从最近一次接口响应推断总页数；如果没有，使用 desktopListTotal 估算
    const total = Number(desktopListTotal.value || 0)
    const limit = Number(desktopFilterQuery.value.limit || 16)
    const totalPages = total > 0 && limit > 0 ? Math.ceil(total / limit) : 1

    // 从第1页开始查找（避免当前页重复，请求时跳过当前页号）
    const currentPage = Number(desktopFilterQuery.value.page || 1)
    for (let p = 1; p <= totalPages; p++) {
      if (p === currentPage) continue
      const query = { ...desktopFilterQuery.value, page: p }
      const res = await fetchDeskList(query)
      let pageList: any[] = []
      if (res?.status === 200 && res?.data) {
        if (Array.isArray(res.data.data)) {
          // 与当前页同构处理：扁平化 recordList
          const tmp: any[] = []
          res.data.data.forEach((item: any) => {
            if (!item || !item.recordList || item.recordList.length === 0) {
              item.hadRecordList = false
              item.isChecked = false
              tmp.push(item)
            } else {
              item.hadRecordList = true
              item.recordList.forEach((record: any) => {
                const recordObj = { recordInfo: { ...record } }
                const newItem = { ...item, ...recordObj, isChecked: false }
                tmp.push(newItem)
              })
            }
          })
          pageList = tmp
        } else if (Array.isArray(res.data)) {
          pageList = res.data
        }
      }

      const matched = pageList.find((d: any) => String(d?.recordInfo?.id) === idVal)
      if (matched) {
        // 找到后跳转到该页并刷新列表，随后当前页流程会完成选中
        desktopFilterQuery.value.page = p
        await getDeskListData(true)
        break
      }
    }
  } finally {
    locatingSelected.value = false
  }
}

// 监听默认选中ID变化
watch(
  () => props.selectedRecordId,
  () => {
    userPaging.value = false
    trySelectDefaultDesk()
  }
)

// 处理选择桌台
const handleSelectTable = (desk: any) => {
  if (userStore.shopWorkStatus !== 1) {
    // isShowWorkingDialog.value = true
    ElMessage.warning('请先开始营业')
    return
  }

  // 先判断是否已经开班（班次管理）
  if (userStore.desktopWorkStatus !== 0) {
    // 如果没有开班，弹出开班弹框
    isShowWorkingDialog.value = true
    return
  }
  // 清除其他桌台的选中状态
  desktopList.value.forEach(item => {
    item.isChecked = false
  })
  // 设置当前桌台为选中状态
  desk.isChecked = true

  // 再判断桌台是否已经开台
  const hasOpened = desk?.hadRecordList === true && desk?.recordInfo
  // 预定单
  if (desk?.is_use?.value === 2) {
    handleOpeningDesktop(desk)
    return
  } else if (!hasOpened) {
    // 如果没有开台，弹出开台弹框
    openingDesk.value = desk
    isShowOpeningDesktopDialog.value = true
  } else {
    // 如果已经开台，再判断桌台是否空闲
    if (desk?.is_use?.value === 0) {
      // 如果空闲，弹出开台弹框
      openingDesk.value = desk
      isShowOpeningDesktopDialog.value = true
    } else {
      // 如果不空闲，正常选择桌台
      emit('selectTable', desk)
      currentDeskDetail.value = desk
    }
  }
}


const handleOpeningDesktop = async (desk: any) => {
  // 获取预订信息
  const bookInfo = desk?.recordInfo || desk?.bookInfo || {}
  
  const content = `
    <div style="padding: 16px; line-height: 1.6; font-size: 14px;">
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">客户姓名:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.user_name  || '-'}</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">联系电话:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.mobile  || '-'}</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">用餐人数:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.use_num}人</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">预订时间:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.book_time.text}</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">预留时长:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.keep_time || '-'}</span>
        </div>
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">预定方式:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.book_type == '1' ? '个人预定': '企业预定'}</span>
        </div>
         <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">开台方式:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.settle_type.text}</span>
        </div>
           
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">预订金:</span>
          <span style="color: #e6a23c; font-weight: 500;">¥${bookInfo.book_money || '0'}</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">单席金额:</span>
          <span style="color: #e6a23c; font-weight: 500;">¥${bookInfo.money  || '0'}</span>
        </div>
        
        <div style="display: flex; align-items: center;">
          <span style="color: #666; min-width: 80px;">预订席数:</span>
          <span style="color: #333; font-weight: 500;">${bookInfo.book_num  || '-'}席</span>
        </div>
      </div>
      
      ${bookInfo.remark? `
        <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #eee;">
          <div style="color: #666; margin-bottom: 4px;">备注信息:</div>
          <div style="color: #333; background: #f8f9fa; padding: 8px; border-radius: 4px; word-break: break-all;">
            ${bookInfo.remark}
          </div>
        </div>
      ` : ''}
    </div>
  `


  const messageInstance = await MessageTips.message(
          {
            title: '预订开台',
            content: content,
            isOnCancel: true,
            onCancelText: '正常开台',
            onSumbitText: '预定开台'
          },
          async () => {
            try {
              messageInstance.setLoading(true)
              const params = { book_id: bookInfo.id }
              const res = await deskBookOpenBookDesk(params)
              if (res?.status === 200) {
                ElMessage.success('开台成功')
                getDeskListData(true)
              }
            } finally {
              messageInstance.setLoading(false)
              messageInstance.close && messageInstance.close()
            }
          },
          () => {
          // 如果没有开台，弹出开台弹框
          openingDesk.value = desk
          isShowOpeningDesktopDialog.value = true
          }
        )
}

// 处理分页数量变化
const handleSizeChange = (size: number) => {
  desktopFilterQuery.value.limit = size
  desktopFilterQuery.value.page = 1
  getDeskListData()
}

// 页码变化（用户手动）
const handlePageChange = (page: number) => {
  userPaging.value = true
  desktopFilterQuery.value.page = page
  getDeskListData()
}

// 处理操作按钮
const handleAction = async (actionType: string) => {
  if (actionType === 'isShowMulOpeningDesktopDialog') {
    isShowMulOpeningDesktopDialog.value = true
  } else if (actionType === 'isShowTransferDesktopDialog') {
    // 转台功能
    if (!currentDeskDetail.value) {
      ElMessage.warning('请先选择桌台')
      return
    }

    // 显示转台组件
    isShowTransferDesktopDialog.value = true
  } else if (actionType === 'isShowShareDesktopDialog') {
    // 搭台功能
    if (!currentDeskDetail.value) {
      ElMessage.warning('请先选择桌台')
      return
    }

    // 显示搭台组件
    isShowShareDesktopDialog.value = true
  } else if (actionType === 'isShowMergeDesktopDialog') {
    // 并台功能
    if (!currentDeskDetail.value) {
      ElMessage.warning('请先选择桌台')
      return
    }

    // 显示并台组件
    isShowMergeDesktopDialog.value = true
  } else if (actionType === 'isShowRevokeDesktopDialog') {
    // 撤台功能
    if (!currentDeskDetail.value) {
      ElMessage.warning('请先选择桌台')
      return
    }

    console.log('当前桌台详情:', currentDeskDetail.value)

    // 判断是否有菜品，如果有菜品则不允许撤台
    const hasFoods = checkHasFoods()
    console.log('检测到菜品结果:', hasFoods)

    if (hasFoods) {
      // 显示菜品清退提示
      const messageTipsInstance = await MessageTips.message(
        {
          title: '菜品清退提示',
          content: '该桌台下还有菜品，请先清退完这些菜品',
          isOnCancel: false,
          onSumbitText: '确定'
        },
        () => {
          messageTipsInstance.close()
        }
      )
      return
    }

    // 获取桌台名称
    const deskName = getDeskName(currentDeskDetail.value)

    // 显示撤台确认对话框
    const messageTipsInstance = await MessageTips.message(
      {
        title: '撤台',
        content: `确定对${deskName}桌进行撤台吗？`,
        isOnCancel: true,
        onCancelText: '取消',
        onSumbitText: '确定'
      },
      async () => {
        try {
          // 设置加载状态
          messageTipsInstance.setLoading(true)

          const datas = {
            // 桌台记录id
            record_id: currentDeskDetail.value.recordInfo.id
          }

          const res = await clearDesk(datas)
          if (res.status === 200) {
            ElMessage.success('撤台成功')
            // 刷新桌台列表
            getDeskListData(true)
            // 关闭对话框
            messageTipsInstance.close()
          } else {
            ElMessage.error('撤台失败')
            messageTipsInstance.setLoading(false)
          }
        } catch (error) {
          console.error('撤台操作失败:', error)
          ElMessage.error('撤台失败')
          messageTipsInstance.setLoading(false)
        }
      }
    )
  }
}

// 检查桌台是否有菜品
const checkHasFoods = () => {
  console.log('检查桌台是否有菜品:', currentDeskDetail.value)

  // 如果有order_foods字段且长度大于0
  if (currentDeskDetail.value?.recordInfo?.order_foods?.length > 0) {
    console.log('发现菜品：order_foods', currentDeskDetail.value.recordInfo.order_foods)
    return true
  }

  // 如果有food_list字段且长度大于0
  if (currentDeskDetail.value?.recordInfo?.food_list?.length > 0) {
    console.log('发现菜品：food_list', currentDeskDetail.value.recordInfo.food_list)
    return true
  }

  // 如果有foodList字段且长度大于0
  if (currentDeskDetail.value?.foodList?.length > 0) {
    console.log('发现菜品：foodList', currentDeskDetail.value.foodList)
    return true
  }

  // 酒席方式特殊结构
  if (currentDeskDetail.value?.foodList?.[0]?.foodList?.length > 0) {
    console.log('发现菜品：foodList[0].foodList', currentDeskDetail.value.foodList[0].foodList)
    return true
  }

  // 检查是否有已点菜品数量
  if (currentDeskDetail.value?.recordInfo?.food_count > 0) {
    console.log('发现菜品：food_count > 0', currentDeskDetail.value.recordInfo.food_count)
    return true
  }

  return false
}

// 获取桌台名称
const getDeskName = (desk: any) => {
  if (desk?.recordInfo?.desk_name) {
    return desk.recordInfo.desk_name
  } else if (desk?.name) {
    return desk.name
  } else {
    return '未知'
  }
}

defineExpose({
  getDeskListData
})
</script>

<style lang="scss" scoped>
.fullWidth {
  width: 1600px !important;
  transition: all 0.5s !important;
}

.desktop-content {
  box-sizing: border-box;
  width: 976px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  transition: all 0.5s;

  &.fullWidth {
    width: 100%;
  }

  .desktop-column-box {
    background: #ffffff;
    border-radius: 20px 20px 0px 0px;
    box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.04);
    padding: 20px 30px;

    .pagingAndSearch-box {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .paging-list-box {
        position: relative;
        box-sizing: border-box;
        width: 700px;
        height: 48px;
        background: #ffffff;
        border: 1px solid #d0d0d0;
        border-radius: 25px;
        display: flex;
        align-items: center;

        .paging-list-item {
          display: inline-block;
          padding: 0 30px;
          height: 48px;
          line-height: 48px;
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;

          .name {
            max-width: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .paging-list-item-active {
          color: #ffffff;
          background: #7c0a03;
          border-radius: 24px;
        }

        .paging-list-btn {
          position: absolute;
          top: 12px;
          right: 16px;
          display: flex;
          align-items: center;

          .left-btn,
          .right-btn {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            cursor: pointer;
          }

          .left-btn {
            margin-right: 20px;
          }
        }
      }

      .search-box {
        display: flex;
        align-items: center;
        width: 192px;
        height: 48px;
        background: #d2d2d2;
        border-radius: 24px;
        box-sizing: border-box;

        .content1 {
          display: flex;
          align-items: center;
          padding-left: 22px;

          > img {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            margin-right: 20px;
          }

          > input {
            font-size: 16px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333;
            border: none;
            outline: none;
            background: transparent;
            width: 120px;
          }

          > input::-webkit-input-placeholder {
            color: #fff;
          }
        }
      }
    }

    .tag-select-box {
      display: flex;
      align-items: center;
      margin-top: 20px;

      .tag-btn-list {
        display: flex;
        align-items: center;

        .tag-btn-item {
          width: 96px;
          height: 40px;
          line-height: 40px;
          border: 1px solid #d2d2d2;
          border-radius: 12px;
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #666666;
          cursor: pointer;
          margin-right: 20px;
        }

        .tag-btn-item-active {
          border-color: #7c0a03 !important;
          color: #7c0a03 !important;
        }
      }

      .tag-status-list {
        display: flex;
        align-items: center;

        .tag-status-item {
          display: flex;
          align-items: center;
          margin-right: 20px;

          .circular {
            width: 14px;
            height: 14px;
            border-radius: 50%;
            margin-right: 12px;
          }

          .name {
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
          }
        }

        .tag-status-item:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .desktop-scroll-list {
    padding: 0 24px;
    height: 670px;
    box-sizing: border-box;
    overflow-y: auto;
    transition: all 0.5s;

    //滚动条整体的大小
    &::-webkit-scrollbar {
      width: 6px;
      height: 0;
    }

    //滚动条里滑动的滑块
    &::-webkit-scrollbar-thumb {
      height: 200px;
      background: #d2d2d2;
      border-radius: 3px;
    }

    //滚动条底层样式
    &::-webkit-scrollbar-track {
      display: none;
    }

    .scroll-list-item-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: space-between;
      box-sizing: border-box;
      padding-bottom: 20px;

      .scroll-list-item {
        position: relative;
        width: 215px;
        height: 210px;
        box-sizing: border-box;
        background: #ffffff;
        border: 1px solid #aa535c;
        border-top: none;
        border-radius: 12px;
        margin-top: 20px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .title-box {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 44px;
          background: #aa535c;
          padding: 0 12px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Bold;
          font-weight: 700;
          color: #ffffff;
          border-radius: 12px 12px 0px 0px;

          .name-box {
            display: flex;
            align-items: center;

            .name {
              font-size: 14px;
              font-weight: bold;
            }

            .lock-icon {
              flex-shrink: 0;
              width: 20px;
              height: 20px;
              margin-left: 10px;
            }
          }

          .count {
            font-size: 14px;
            font-weight: bold;
          }
        }

        .desc-box {
          padding: 10px 0 0 12px;

          .numberAndTag {
            display: flex;
            align-items: flex-start;

            .number {
              max-width: 200px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              font-size: 36px;
              font-family:
                PingFang SC,
                PingFang SC-Bold;
              font-weight: 700;
              color: #434447;
            }

            .tag {
              display: inline-block;
              padding: 0 10px;
              height: 20px;
              line-height: 20px;
              background: #cba699;
              border-radius: 10px 10px 10px 0px;
              font-size: 14px;
              font-family:
                PingFang SC,
                PingFang SC-Bold;
              font-weight: 700;
              text-align: center;
              color: #ffffff;
              margin-left: 4px;
            }
          }

          .price {
            margin-top: 10px;
            font-size: 18px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            color: #384148;
          }

          .time1 {
            margin-top: 10px;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #333333;
          }

          .time2 {
            display: flex;
            align-items: center;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333333;
            margin-top: 0px;

            > div {
              margin-right: 10px;
            }
          }
        }

        .book-info-box {
          padding: 0 0 0 12px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
        }

        .choose-img {
          position: absolute;
          right: 12px;
          bottom: 12px;
          width: 24px;
          height: 24px;
        }
      }

      .scroll-list-item-zhanwei {
        width: 215px;
        overflow: hidden;
      }
    }

    .no-data-box {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 170px;
      margin-top: 250px;
    }
  }

  .desktop-count-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;

    .left {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: left;
      color: #666666;
    }
  }

  .desktop-actions-btn-box {
    width: 976px;
    height: 100px;
    box-sizing: border-box;
    padding: 0 30px;
    background: #ffffff;
    box-shadow: 0px -4px 6px 0px rgba(0, 0, 0, 0.04);
    border-radius: 0px 0px 20px 20px;
    transition: all 0.5s;

    .btn-list {
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .btn-item {
        display: inline-block;
        padding: 0 30px;
        height: 48px;
        line-height: 48px;
        background: #ffffff;
        border: 1px solid #333333;
        border-radius: 12px;
        cursor: pointer;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #333333;
        margin-left: 30px;
        transition: all 0.3s;

        &:hover {
          border-color: #7c0a03 !important;
          color: #7c0a03 !important;
        }
      }
    }
  }
}
</style>
